package util

import (
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"hash"
	"strings"
)

// Sha1Stream :
type Sha1Stream struct {
	_sha1 hash.Hash
}

// Update ：
func (obj *Sha1Stream) Update(data []byte) {
	if obj._sha1 == nil {
		obj._sha1 = sha1.New()
	}
	obj._sha1.Write(data)
}

// Sum :
func (obj *Sha1Stream) Sum() string {
	return hex.EncodeToString(obj._sha1.Sum([]byte("")))
}

// Sha1 :
func Sha1(data []byte) string {
	_sha1 := sha1.New()
	_sha1.Write(data)
	return hex.EncodeToString(_sha1.Sum([]byte("")))
}

//MD5 : 计算MD5
func MD5(data []byte) string {
	_md5 := md5.New()
	_md5.Write(data)
	return hex.EncodeToString(_md5.Sum([]byte("")))
}

//IsStrValid : 判断字符串是否合法
func IsStrValid(s string) bool {
	if len(s) <= 0 {
		return false
	}
	for i := 0; i < len(s); i++ {
		if !((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f') || (s[i] >= 'A' && s[i] <= 'F')) {
			return false
		}
	}
	return true
}

// Char2Int : 将字符转换为对应的int64类型
func Char2Int(c int32) (num int64) {
	switch c {
	case '0':
		num = 0
	case '1':
		num = 1
	case '2':
		num = 2
	case '3':
		num = 3
	case '4':
		num = 4
	case '5':
		num = 5
	case '6':
		num = 6
	case '7':
		num = 7
	case '8':
		num = 8
	case '9':
		num = 9
	case 'a':
		num = 10
	case 'b':
		num = 11
	case 'c':
		num = 12
	case 'd':
		num = 13
	case 'e':
		num = 14
	case 'f':
		num = 15
	default:
		num = -1
	}
	return
}

//Str16toInt : 将16进制字符串转为int64类型
func Str16toInt(s string) int64 {
	s = strings.ToLower(s)
	if !IsStrValid(s) {
		return -1
	}
	var num int64
	for i := 0; i < len(s); i++ {
		num = num*16 + Char2Int(int32(s[i]))
	}
	return num
}
